package net.openvision.music.model;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeSet;

import net.openvision.music.model.event.GlobalVariableChangeEvent;

public class ScoreEnvironment {
	private List<Map<Class<?>, SortedSet<GlobalVariableChangeEvent<?>>>> events;
	
	public ScoreEnvironment() {
		events = new ArrayList<Map<Class<?>, SortedSet<GlobalVariableChangeEvent<?>>>>();
	}
	
	public void addEvent(GlobalVariableChangeEvent<?> event) {
		if (events.size() <= event.getStaffNr()) {
			for (int i = events.size(); i <= event.getStaffNr(); i++) {
				events.add(new HashMap<Class<?>, SortedSet<GlobalVariableChangeEvent<?>>>());
			}
		}
		SortedSet<GlobalVariableChangeEvent<?>> c = events.get(event.getStaffNr()).get(event.getType());
		if (c == null) {
			c = new TreeSet<GlobalVariableChangeEvent<?>>();
			events.get(event.getStaffNr()).put(event.getClass(), c);
		}
		c.add(event);
	}
	
	@SuppressWarnings("unchecked")
	public <T> T getValueAt(int staffNr, int barNr, Length position, Class<T> type) {
		/* TODO: korrekt implementieren */
		SortedSet<GlobalVariableChangeEvent<?>> c = events.get(staffNr).get(type);
		T result = null;
		for (GlobalVariableChangeEvent<?> e:c) {
			if (e.getBarNr() > barNr) {
				return result;
			}
			result = (T)e.getObject();	
		}
		return result;
	}
	
}
